package net.zjitc.controller;

import net.zjitc.common.ResponseResult;
import net.zjitc.entity.Category;
import net.zjitc.exception.CategoryException;
import net.zjitc.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 毛钰深
 * @Create 2022/1/4 13:14
 * 商品分类
 */
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PreAuthorize("hasAuthority('149')")
    @GetMapping("/categories")
    public ResponseResult getCategories(@RequestParam(required = false) Integer type,
                                        @RequestParam(required = false) Integer pagenum,
                                        @RequestParam(required = false) Integer pagesize){
    ResponseResult res;
        try {
            if (pagenum == null||pagesize==null){
                res= categoryService.getCategories(type);
            }else{
                res=categoryService.getPageCategories(type,pagenum,pagesize);
            }
        } catch (CategoryException e) {
            res=new ResponseResult();
            res.setError(e.getMessage());
        }
        return res;
    }

    @PreAuthorize("hasAuthority('122')")
    @PostMapping("/categories")
    public ResponseResult addCategory(@RequestBody Category category){
        ResponseResult res;
        if (category.getCat_pid()!=null&&category.getCat_name()!=null&&category.getCat_level()!=null&&!"".equals(category.getCat_name())){
            Category cate=new Category();
            cate.setCatName(category.getCat_name());
            cate.setCat_pid(category.getCat_pid());
            cate.setCatLevel(category.getCat_level());
            try {
                res=categoryService.addCategory(cate);
            } catch (CategoryException e) {
                res=new ResponseResult();
                res.setError(e.getMessage());
            }
        }else{
            res=new ResponseResult();
            res.setUnprocesableEntity("所需参数为空");
        }
        return res;
    }

    @PreAuthorize("hasAuthority('149')")
    @GetMapping("/categories/{id}")
    public ResponseResult selectById(@PathVariable Integer id){
        return categoryService.selectById(id);
    }

    @PreAuthorize("hasAuthority('161')")
    @PutMapping("/categories/{id}")
    public ResponseResult updateCategory(@PathVariable Integer id,@RequestBody Category category){
        return categoryService.updateCategory(id,category);
    }

    @PreAuthorize("hasAuthority('123')")
    @DeleteMapping("/categories/{id}")
    public ResponseResult deleteCategory(@PathVariable Integer id){
        return categoryService.deleteCategory(id);
    }
}
